//index.js
//获取应用实例
const app = getApp()
var that = null;
Page({
  data: {
    loginData:{
      url:"http://112.74.214.177:18080/physic/loginXCX",
      isLogin:false,
      sessionID:null
    },
    totalCount:0,
    totalMoney:0,
    goodsRow: [],
      orderUrl:"http://112.74.214.177:18080/physic/slSale/calculateDetail",       qryByCodeUrl:"http://112.74.214.177:18080/physic/psDispensaryStock/listForXS",
    
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },


 /**
  * 获取商品信息
  */
  goods_getInfo:function(){
    that = this;
    //如果没有登录先登录
    if (!this.data.loginData.isLogin){
     
      wx.request({
        url: that.data.loginData.url,
        data: {
          code: "1234",
          autologinch: "justtest",
          loginname: "admin",
          password: "2"
        },
        success: function (res) {
          console.log(res)
          if (res.data.success) { //如果登录成功
            //修改登录状态
            that.setData({
              "loginData.isLogin": true,
              "loginData.sessionID": res.data.sessionID
            })
            scanGoodsCode(that)
          } else { //显示登录失败信息
            wx.showToast({
              title: '请先登录',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }else{
      scanGoodsCode(that);
    }
    
  },
 
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          console.log(res)
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * 下单函数
   */
  order:function(){
    wx.showLoading({
      title: '下单中'
    })
    wx.request({
      url: that.data.orderUrl,
      data: {
        rows: that.data.goodsRow,
        totalMoney: that.data.totalMoney,
        totalCount: that.data.totalCount
      },
      success: function (res) {
        console.log("下单成功");
        wx.hideLoading();
      }
    })
  },
  /**
   * 改变商品数量 ，加或者减少数量
   */
  changecount:function(e){
    console.log(e)
    var gid = e.currentTarget.dataset.gid;
    var cgtype = e.currentTarget.dataset.type;
    var rows = that.data.goodsRow;
    var totalCount = 0;
    var totalMoney = 0;
    for (var i in rows){
      var gcount = rows[i].count;
      if(rows[i].id==gid){
        if(cgtype == 1){
          if (gcount >1){
            gcount = gcount-1;
          }
        } else {
          gcount = gcount + 1;
        }
        rows[i].count = gcount;
      }
      totalCount += gcount;
      totalMoney += gcount * rows[i].sellprice
    }
    that.setData({
      goodsRow:rows,
      totalCount: totalCount,
      totalMoney: totalMoney
    })
  }
})

/**
 * 处理数据
 */
function handleData(res){
  var dd = res.rows;
  //以下是测试数据
  dd = [
    {
      "id": "9628cc329642479cb07f0720e3953be1", "unit_id": "1", "physic_code": "2", "physic_std_code": "1", "quantity": 6, "temp_quantity": 6, "in_price": 1.0000, "trade_price": 1.0000, "retail_price": 1.0000, "last_update": 1521818469000, "batch_number": null, "validity": "2017-01-01", "physic_name": null,
      "physicDict": { "id": "0aaea2463abd4835b05336721b5722b6", "physic_type": "2", "physic_code": "2", "physic_name_code": "2", "physic_name": "2", "mnemonic": "2", "physic_spec": "2", "physic_unit": "2", "physic_form": "2", "toxicology_property": "2", "material_property": "2", "item_receipt": "2", "condition_of_storage": "2", "dose_per_unit": "1.000", "dose_unit": "2", "valid_flag": "2", "drug_use_level": "2", "drugs_category": "2", "explanation": "2", "operator": "sa", "operate_date": 1520348356000, "presc_flag": "1", "approvalnum": "2", "manufactor_code": "2", "approvalnum_remark": "2", "remark": "2", "barcode": "2" }
    },
    {
      "id": "c6f3e0b9a35b40f2b2bc2b952b4a4d27", "unit_id": "1", "physic_code": "1", "physic_std_code": "1", "quantity": 1, "temp_quantity": 1, "in_price": 1.0000, "trade_price": 1.0000, "retail_price": 20.0000, "last_update": 1483200000000, "batch_number": "1", "validity": "1", "physic_name": null,
      "physicDict": { "id": "77ba0207febb4cf3b4d6775917521537", "physic_type": "yp", "physic_code": "1", "physic_name_code": "1", "physic_name": "1", "mnemonic": "1", "physic_spec": "1", "physic_unit": "1", "physic_form": "1", "toxicology_property": "1", "material_property": "1", "item_receipt": "1", "condition_of_storage": "1", "dose_per_unit": "1.000", "dose_unit": "1", "valid_flag": "1", "drug_use_level": "1", "drugs_category": "1", "explanation": "1", "operator": "sa", "operate_date": 1521097151000, "presc_flag": "1", "approvalnum": "1", "manufactor_code": "22", "approvalnum_remark": "1", "remark": "1", "barcode": "1" }
    }]
  var datas = [];
  var totalCount = 0;
  var totalMoney = 0;
  for(var i in dd){
    totalCount += 1;
    totalMoney += dd[i].retail_price
     var a = {
       name: dd[i].physicDict.physic_name,
       physic_code: dd[i].physicDict.physic_code,
       sellprice: dd[i].retail_price,
       count:1,
       id:dd[i].id
     }
     datas.push(a)
  }
  that.setData({
    goodsRow: datas,
    totalCount: totalCount,
    totalMoney: totalMoney
  })
  console.log("data");
  console.log(that.data.goodsRow);
  wx.hideLoading();
}

/**
 * 扫描商品二维码
 */
function scanGoodsCode(that) {
  //调用扫描接口
  wx.scanCode({
    onlyFromCamera: true,
    success: (res) => {
      console.log(res)
      var resCode = res.result;
      //获取商品信息
      wx.showLoading({
        title: '数据加载中',
      })
      console.log("开始获取数据")
      wx.request({
        url: that.data.qryByCodeUrl,
        data: {
          searchString: resCode, //商品的编码
          sessionID: that.data.loginData.sessionID
        },
        success: function (res) {
          handleData(res);
        }
      })
    }
  })
}
